from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey, Enum, Boolean
from sqlalchemy.orm import relationship
from datetime import datetime
from backend.database import Base
import enum

class DeviceType(str, enum.Enum):
    CISCO_IOS = "cisco_ios"
    CISCO_XE = "cisco_xe"
    CISCO_ASA = "cisco_asa"
    HUAWEI = "huawei"
    H3C = "hp_comware"
    JUNIPER = "juniper"
    ARISTA = "arista_eos"
    OTHER = "autodetect"

class BackupStatus(str, enum.Enum):
    SUCCESS = "success"
    FAILED = "failed"
    IN_PROGRESS = "in_progress"

class Device(Base):
    __tablename__ = "devices"
    
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(100), nullable=False, unique=True)
    hostname = Column(String(255), nullable=False)
    ip_address = Column(String(50), nullable=False)
    device_type = Column(String(50), nullable=False)
    port = Column(Integer, default=22)
    username = Column(String(100), nullable=False)
    password = Column(String(255), nullable=False)  # 实际应该加密存储
    enable_password = Column(String(255), nullable=True)
    description = Column(Text, nullable=True)
    is_active = Column(Boolean, default=True)
    auto_backup = Column(Boolean, default=True)
    backup_interval = Column(Integer, default=24)  # 备份间隔（小时）
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
    
    # 关系
    backups = relationship("Backup", back_populates="device", cascade="all, delete-orphan")

class Backup(Base):
    __tablename__ = "backups"
    
    id = Column(Integer, primary_key=True, index=True)
    device_id = Column(Integer, ForeignKey("devices.id", ondelete="CASCADE"), nullable=False)
    filename = Column(String(255), nullable=True)  # 允许为空
    filepath = Column(String(500), nullable=True)  # 允许为空
    file_size = Column(Integer, default=0)  # 字节
    status = Column(String(20), default=BackupStatus.SUCCESS)
    error_message = Column(Text, nullable=True)
    backup_time = Column(DateTime, default=datetime.utcnow)
    is_manual = Column(Boolean, default=False)  # 是否手动触发
    config_hash = Column(String(64), nullable=True)  # MD5哈希，用于检测配置变化
    
    # 关系
    device = relationship("Device", back_populates="backups")

class ScheduleLog(Base):
    __tablename__ = "schedule_logs"
    
    id = Column(Integer, primary_key=True, index=True)
    job_name = Column(String(100), nullable=False)
    status = Column(String(20), nullable=False)
    message = Column(Text, nullable=True)
    devices_count = Column(Integer, default=0)
    success_count = Column(Integer, default=0)
    failed_count = Column(Integer, default=0)
    execute_time = Column(DateTime, default=datetime.utcnow)

